package org.vnetcon.blobdb.client;

import org.vnetcon.blobdb.shared.FieldVerifier;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class BlobDB implements EntryPoint {

	final Button btnQueryTable = new Button("Execute bSQL");
	final Button btnUserTable = new Button("BlobDB users");
	final Button btnDriverTable = new Button("BlobDB drivers");
	final Button btnHelpTable = new Button("BlobDB help");
	
	final TextArea query = new TextArea();
	final Button executeQuery = new Button("Execute");
	
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final BlobDBUIServiceAsync greetingService = GWT
			.create(BlobDBUIService.class);

	private void setLoginUrl(){
		greetingService.getLoginUrl("some text",
				new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				InlineHTML il = new InlineHTML("Failed to get login url: " + caught.getMessage());
				RootPanel.get("login").add(il);
			}
			
			public void onSuccess(String resultx) {
				String loginUrl = "Please login as BlobDB application administrator using Google account: <a href=\"" + resultx + "\"> Login</a>";
				InlineHTML il = new InlineHTML(loginUrl);
				RootPanel.get("login").add(il);
			}
			
		});
	}

	private void setLogoutUrl(){
		greetingService.getLogoutUrl("some text",
				new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				InlineHTML il = new InlineHTML("Failed to get logout url: " + caught.getMessage());
				RootPanel.get("login").add(il);
			}
			
			public void onSuccess(String resultx) {
				String loginUrl = "<a href=\"" + resultx + "\">Logout</a>";
				InlineHTML il = new InlineHTML(loginUrl);
				RootPanel.get("login").add(il);
			}
			
		});
	}
	
	public void onModuleLoad() {

		greetingService.isAdmin("some text",
				new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						InlineHTML il = new InlineHTML(caught.getMessage());
						RootPanel.get("resultsTable").add(il);
					}

					public void onSuccess(String result) {
						if(result.equals("no")){
							btnQueryTable.setEnabled(false);
							btnUserTable.setEnabled(false);
							btnDriverTable.setEnabled(false);
							btnHelpTable.setEnabled(false);
//							executeQuery.setVisible(false);
							
							RootPanel.get("queryTable").setVisible(false);
							RootPanel.get("resultsTable").setVisible(false);
							RootPanel.get("userTable").setVisible(false);
							RootPanel.get("driverTable").setVisible(false);
							RootPanel.get("helpTable").setVisible(false);

							setLoginUrl();
							
							return;
						}else{
							setLogoutUrl();
						}
					}
				});
		
		
		
		btnQueryTable.setEnabled(false);
		RootPanel.get("driverTable").setVisible(false);
		RootPanel.get("userTable").setVisible(false);
		RootPanel.get("helpTable").setVisible(false);
		
		RootPanel.get("btnQueryTable").add(btnQueryTable);
		RootPanel.get("btnUserTable").add(btnUserTable);
		RootPanel.get("btnDriverTable").add(btnDriverTable);
		RootPanel.get("btnHelpTable").add(btnHelpTable);

		
		btnQueryTable.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				btnQueryTable.setEnabled(false);
				btnUserTable.setEnabled(true);
				btnDriverTable.setEnabled(true);
				btnHelpTable.setEnabled(true);
				
				RootPanel.get("queryTable").setVisible(true);
				RootPanel.get("resultsTable").setVisible(true);
				RootPanel.get("userTable").setVisible(false);
				RootPanel.get("driverTable").setVisible(false);
				RootPanel.get("helpTable").setVisible(false);
				
			}
		});

		btnUserTable.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				btnQueryTable.setEnabled(true);
				btnUserTable.setEnabled(false);
				btnDriverTable.setEnabled(true);
				btnHelpTable.setEnabled(true);
				
				RootPanel.get("queryTable").setVisible(false);
				RootPanel.get("resultsTable").setVisible(false);
				RootPanel.get("userTable").setVisible(true);
				RootPanel.get("driverTable").setVisible(false);
				RootPanel.get("helpTable").setVisible(false);
				
			}
		});
		
		btnDriverTable.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				btnQueryTable.setEnabled(true);
				btnUserTable.setEnabled(true);
				btnDriverTable.setEnabled(false);
				btnHelpTable.setEnabled(true);
				
				RootPanel.get("queryTable").setVisible(false);
				RootPanel.get("resultsTable").setVisible(false);
				RootPanel.get("userTable").setVisible(false);
				RootPanel.get("driverTable").setVisible(true);
				RootPanel.get("helpTable").setVisible(false);
				
			}
		});
		
		btnHelpTable.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				btnQueryTable.setEnabled(true);
				btnUserTable.setEnabled(true);
				btnDriverTable.setEnabled(true);
				btnHelpTable.setEnabled(false);
				
				RootPanel.get("queryTable").setVisible(false);
				RootPanel.get("resultsTable").setVisible(false);
				RootPanel.get("userTable").setVisible(false);
				RootPanel.get("driverTable").setVisible(false);
				RootPanel.get("helpTable").setVisible(true);
				
			}
		});
		
		
		query.setWidth("800px");
		query.setHeight("200px");
		
		RootPanel.get("query").add(query);
		RootPanel.get("executeBtn").add(executeQuery);
		
		executeQuery.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				executeQuery();
			}
		});
		
	}

	
	private void executeQuery(){
		String bSQL = this.query.getText();
		InlineHTML il = new InlineHTML("<table border=\"1\"><tr><td>Results....</td></tr></table>");
		RootPanel.get("resultsTable").clear();
		
		greetingService.executeQuery(bSQL,
				new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						InlineHTML il = new InlineHTML(caught.getMessage());
						RootPanel.get("resultsTable").add(il);
					}

					public void onSuccess(String result) {
						InlineHTML il = new InlineHTML(result);
						RootPanel.get("resultsTable").add(il);
					}
				});
		
	}
	
	public void xxx_onModuleLoad() {
		greetingService.greetServer("hello server",
				new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
					}

					public void onSuccess(String result) {
					}
				});
	}
	
	
	/**
	 * This is the entry point method.
	 */
	public void xx_onModuleLoad() {
		final Button sendButton = new Button("Send");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User");
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				String textToServer = nameField.getText();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
	}
}
